package ui

import (
	"encoding/json"
	"fmt"
	"log"

	"diff.wang/devtool/entity"
	"diff.wang/devtool/service"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
)

func IpInfoUi() (info *widget.Form, ip, location, isp *widget.Label) {

	// 组件定义
	ip = widget.NewLabel("")
	location = widget.NewLabel("")
	isp = widget.NewLabel("")

	// 表单显示
	info = widget.NewForm(
		&widget.FormItem{Text: "IP地址:", Widget: ip},
		&widget.FormItem{Text: "所属地:", Widget: location},
		&widget.FormItem{Text: "服务商:", Widget: isp},
	)
	return
}

func IPForm(w fyne.Window, ip, loc, isp *widget.Label) (form *widget.Form) {
	// 初始化 ip 输入框
	ipInput := widget.NewEntry()
	// 设置提示信息
	ipInput.SetPlaceHolder("请输入IP地址")

	// 定义表单和触发事件
	form = &widget.Form{
		SubmitText: "确认",
		Items: []*widget.FormItem{ // we can specify items in the constructor
			{Text: "IP", Widget: ipInput}},
		OnSubmit: func() { // optional, handle form submission
			res, err := service.GetIpInfo(ipInput.Text)
			log.Println(res, err)
			if err != nil {
				d := dialog.NewError(err, w)
				d.Show()
				return
			}
			var entityIp entity.IpResponseEntity
			err = json.Unmarshal([]byte(res), &entityIp)
			if err != nil {
				d := dialog.NewError(err, w)
				
				d.Show()
				return
			}
			ip.SetText(entityIp.Query)
			s := fmt.Sprintf("%s %s %s", entityIp.Country, entityIp.RegionName, entityIp.City)
			loc.SetText(s)
			isp.SetText(entityIp.Isp)
			ipInput.SetText("")
			// ipInfo(res)
		},
	}

	// 初始化说明信息
	infoText := widget.NewLabel("输入IP地址查询IP信息")
	form.Append("说明", infoText)
	return
}
